import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../layout/Index.vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { nextTick } from 'vue'
import FrontLayout from '@/layout/FrontLayout.vue'

const routes = [
  {
    path: '/',
    redirect: '/front/home'  // 将根路径重定向到前台首页
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/register/index.vue'),
    meta: { title: '注册' }
  },
  {
    path: '/admin',
    component: Layout,
    meta: { requiresAuth: true, requiresAdmin: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/admin/dashboard/index.vue'),
        meta: { title: '首页', requiresAuth: true }
      },
      {
        path: 'questionnaire',
        name: 'QuestionnaireList',
        component: () => import('@/views/questionnaire/Index.vue'),
        meta: { title: '问卷管理' }
      },
      {
        path: 'questionnaire/add',
        name: 'QuestionnaireAdd',
        component: () => import('@/views/questionnaire/Detail.vue'),
        meta: { title: '新增问卷' }
      },
      {
        path: 'questionnaire/edit/:id',
        name: 'QuestionnaireEdit',
        component: () => import('@/views/questionnaire/Detail.vue'),
        meta: { title: '编辑问卷' }
      },
      {
        path: 'announcement',
        name: 'Announcement',
        component: () => import('@/views/announcement/List.vue'),
        meta: { title: '公告管理', requiresAuth: true }
      },
      {
        path: 'announcement/add',
        name: 'AnnouncementAdd',
        component: () => import('@/views/announcement/Add.vue'),
        meta: { title: '发布公告', requiresAuth: true }
      },
      {
        path: 'message',
        name: 'Message',
        component: () => import('../views/message/Index.vue')
      },
      {
        path: 'forum',
        name: 'Forum',
        component: () => import('../views/forum/Index.vue')
      },
      {
        path: 'news',
        name: 'News',
        component: () => import('@/views/news/List.vue'),
        meta: { title: '新闻管理', requiresAuth: true }
      },
      {
        path: 'news/add',
        name: 'NewsAdd',
        component: () => import('@/views/news/Add.vue'),
        meta: { title: '发布新闻', requiresAuth: true }
      },
      {
        path: 'news/edit/:id',
        name: 'NewsEdit',
        component: () => import('@/views/news/Edit.vue'),
        meta: { title: '编辑新闻', requiresAuth: true }
      },
      {
        path: 'statistics',
        name: 'Statistics',
        component: () => import('@/views/statistics/Index.vue'),
        meta: { title: '统计分析', icon: 'Histogram' }
      },
      {
        path: '/questionnaire/detail/:id?',
        name: 'QuestionnaireDetail',
        component: () => import('@/views/questionnaire/Detail.vue'),
        meta: { title: '问卷详情' }
      },
      {
        path: '/questionnaire/submit/:id',
        name: 'QuestionnaireSubmit',
        component: () => import('@/views/questionnaire/Submit.vue'),
        meta: { title: '问卷填写' }
      },
      {
        path: '/questionnaire/statistics/:id',
        name: 'QuestionnaireStatistics',
        component: () => import('@/views/questionnaire/Statistics.vue'),
        meta: { title: '问卷统计' }
      },
      {
        path: '/questionnaire/my-submissions',
        component: () => import('@/views/questionnaire/MySubmissions.vue'),
        meta: { title: '我的提交', requiresAuth: true }
      },
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/user/Index.vue'),
        meta: { 
          title: '用户管理',
          requiresAuth: true,
          requiresAdmin: true // 只有管理员可以访问
        }
      },
      {
        path: 'questionnaire/fill/:id',
        name: 'QuestionnaireFill',
        component: () => import('@/views/questionnaire/Fill.vue'),
        meta: { 
          title: '填写问卷'
        }
      },
      {
        path: 'carousel',
        name: 'CarouselManage',
        component: () => import('@/views/admin/CarouselManage.vue'),
        meta: { 
          title: '轮播图管理', 
          icon: 'picture',
          requiresAuth: true,
          requiresAdmin: true
        }
      },
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('@/views/user/Profile.vue'),
        meta: {
          title: '个人中心',
          requiresAuth: true
        }
      },
      {
        path: 'statistics',
        name: 'UserStatistics',
        component: () => import('@/views/user/Statistics.vue'),
        meta: {
          title: '统计信息',
          requiresAuth: true
        }
      },
      {
        path: '/admin/news',
        component: () => import('@/views/news/List.vue'),
        meta: { title: '新闻管理', requiresAuth: true, requiresAdmin: true }
      },
      {
        path: '/admin/news/add',
        component: () => import('@/views/news/Add.vue'),
        meta: { title: '发布新闻', requiresAuth: true, requiresAdmin: true }
      },
      {
        path: '/admin/news/edit/:id',
        component: () => import('@/views/news/Edit.vue'),
        meta: { title: '编辑新闻', requiresAuth: true, requiresAdmin: true }
      },
      {
        path: '/admin/announcement',
        component: () => import('@/views/announcement/List.vue'),
        meta: { title: '公告管理', requiresAuth: true, requiresAdmin: true }
      },
      {
        path: '/admin/announcement/add',
        component: () => import('@/views/announcement/Add.vue'),
        meta: { title: '发布公告', requiresAuth: true, requiresAdmin: true }
      },
      {
        path: '/admin/announcement/edit/:id',
        component: () => import('@/views/announcement/Edit.vue'),
        meta: { title: '编辑公告', requiresAuth: true, requiresAdmin: true }
      }
    ]
  },
  // 前台路由
  {
    path: '/front',
    component: FrontLayout,
    children: [
      {
        path: 'home',
        name: 'FrontHome',
        component: () => import('@/views/front/Home.vue'),
        meta: { title: '首页' }
      },
      {
        path: 'news',
        name: 'FrontNews',
        component: () => import('@/views/front/News.vue'),
        meta: { title: '新闻资讯' }
      },
      {
        path: 'news/:id',
        name: 'FrontNewsDetail',
        component: () => import('@/views/front/NewsDetail.vue'),
        meta: { title: '新闻详情' }
      },
      {
        path: 'announcements',
        name: 'FrontAnnouncements',
        component: () => import('@/views/front/Announcements.vue'),
        meta: { title: '公告列表' }
      },
      {
        path: 'announcements/:id',
        name: 'FrontAnnouncementDetail',
        component: () => import('@/views/front/AnnouncementDetail.vue'),
        meta: { title: '公告详情' }
      },
      {
        path: 'questionnaires',
        name: 'FrontQuestionnaires',
        component: () => import('@/views/front/Questionnaires.vue'),
        meta: { title: '问卷列表' }
      },
      {
        path: 'questionnaires/:id/fill',
        name: 'QuestionnaireFill',
        component: () => import('@/views/front/QuestionnaireFill.vue'),
        meta: { title: '填写问卷' }
      },
      {
        path: 'profile',
        name: 'FrontProfile',
        component: () => import('@/views/front/Profile.vue'),
        meta: { title: '个人中心', requiresAuth: true }
      },
      {
        path: 'my-submissions',
        name: 'FrontMySubmissions',
        component: () => import('@/views/front/MySubmissions.vue'),
        meta: { 
          title: '我的提交记录',
          requiresAuth: true 
        }
      },
      {
        path: 'forum',
        name: 'FrontForum',
        component: () => import('@/views/front/forum/Index.vue'),
        meta: { title: '论坛' }
      },
      {
        path: 'forum/post/:id',
        name: 'FrontForumPost',
        component: () => import('@/views/front/forum/Post.vue'),
        meta: { title: '帖子详情' }
      },
      {
        path: 'forum/create',
        name: 'FrontForumCreate',
        component: () => import('@/views/front/forum/Create.vue'),
        meta: { title: '发布帖子', requiresAuth: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    return { top: 0 }  // 切换路由时滚动到顶部
  }
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 检查是否需要登录
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
    // 如果是个人中心相关页面，确保用户信息已加载
    if (to.path.includes('/profile') || to.path.includes('/statistics')) {
      if (!userStore.user) {
        userStore.loadUserInfo().catch(() => {
          ElMessage.error('获取用户信息失败')
          next('/login')
        })
      }
    }
  }
  
  // 检查管理员权限
  if (to.matched.some(record => record.meta.requiresAdmin)) {
    if (!userStore.isAdmin) {
      ElMessage.error('无权访问')
      next(from.path)
      return
    }
  }

  // 如果已登录，访问登录页面时重定向到首页
  if (userStore.isLoggedIn && (to.path === '/login' || to.path === '/register')) {
    next('/')
    return
  }

  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 问卷调查系统` : '问卷调查系统'

  // 确保组件重新渲染
  nextTick()
  next()
})

export default router 